package com.example.userservice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.commonservice.Common.Result;
import com.example.userservice.entity.VolunteerProfile;
import com.example.userservice.service.VolunteerProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class VolunteerProfileController {
    @Autowired
    private VolunteerProfileService profileService;
    // 志愿者档案管理接口
    @GetMapping("/profile/list")
    public Result<IPage<VolunteerProfile>> listProfiles(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String realName,
            @RequestParam(required = false) String school,
            @RequestParam(required = false) Integer status) {

        Map<String, Object> params = new HashMap<>();
        params.put("realName", realName);
        params.put("school", school);
        params.put("status", status);
        return Result.success(profileService.pageProfiles(current, size, params));
    }

    @PostMapping("/profile/add")
    public Result<String> addProfile(@RequestBody VolunteerProfile profile) {
        profile.setCreateTime(LocalDateTime.now());
        profileService.save(profile);
        return Result.success("志愿者档案新增成功，ID：" + profile.getId());
    }

    @PostMapping("/profile/delete")
    public Result<String> deleteProfile(@RequestParam Long id) {
        boolean success = profileService.removeById(id);
        return success ? Result.success("志愿者档案删除成功") : Result.error("档案不存在，删除失败");
    }

    @PostMapping("/profile/update")
    public Result<String> updateProfile(@RequestBody VolunteerProfile profile) {
        boolean success = profileService.updateById(profile);
        return success ? Result.success("志愿者档案更新成功") : Result.error("档案不存在，更新失败");
    }

    @GetMapping("/profile/getVolunteerName/{id}")
    public Result<String> getVolunteerName(@PathVariable Long id) {
        VolunteerProfile profile = profileService.getById(id);
        return profile != null ? Result.success(profile.getRealName()) : Result.error("志愿者不存在");
    }
    @GetMapping("/profile/getVolunteerId/{userId}")
    public Result<Long> getVolunteerId(@PathVariable Long userId) {
        System.out.println("userId:"+userId);
        // 使用条件查询，根据userId字段查询志愿者档案
        VolunteerProfile profile = profileService.lambdaQuery()
                .eq(VolunteerProfile::getUserId, userId)
                .one();
        return profile != null ? Result.success(profile.getId()) : Result.error("志愿者不存在");
    }
}
